package main

import (
	"fmt"
	"io"
	"os"
	"path"

	"time"
)

func main() {
	var fileName = "./tmp/ddd.txt"
	f, err := createFile(fileName)

	if err != nil {
		fmt.Println("创建文件失败:", err.Error())
		return
	}
	str := []string{"1", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2"}
	fmt.Println("创建文件成功")
	for _, v := range str {
		n, err := io.WriteString(f, v+"\n")
		if err != nil {
			fmt.Println("写入文件失败")
			return
		}
		fmt.Println("写入的字节数:", n)
		time.Sleep(3 * time.Second)
	}
	f.Close()
	f, err = createFile(fileName)
	bytes, _ := io.ReadAll(f)
	fmt.Println("所有的字节数:", string(bytes))
}

func createFile(filePath string) (f *os.File, err error) {
	// os.OpenFile(filename, os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0766)

	var exist = true
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		exist = false
	}

	if exist {
		fileName, err := os.OpenFile(filePath, os.O_RDWR, 0766)
		if err != nil {
			return nil, err
		}
		return fileName, nil
	}

	// 文件不存在, 创建文件
	err = os.MkdirAll(path.Dir(filePath), 0755)
	if err != nil {
		fmt.Println("创建目录失败", err)
		return nil, err
	}
	filename, err := os.Create(filePath)
	if err != nil {
		return nil, err
	}
	return filename, nil
}
